<?php
declare (strict_types=1);

namespace app\api\controller;

use app\common\model\UserAuth as UserAuthModel;
use app\common\tool\Result;
use think\exception\ValidateException;
use think\Response;

class UserAuth extends Base
{
    public function index(): Response
    {
        $data = [
            'real_name' => '',
            'id_card' => '',
            'img_front' => '',
            'img_back' => '',
            'is_edit' => 1,
            'status' => '待认证',
            'reject_msg' => ''
        ];
        if (!empty($this->user->id_card)) {
            $data = [
                'real_name' => $this->user->real_name,
                'id_card' => $this->user->id_card,
                'img_front' => $this->user->img_front,
                'img_back' => $this->user->img_back,
                'is_edit' => 0,
                'status' => '已认证',
                'reject_msg' => ''
            ];
        } else {
            $info = UserAuthModel::where(['uid' => $this->user->id])->order('id desc')->find();
            if ($info) {
                $data = [
                    'real_name' => $info->real_name,
                    'id_card' => $info->id_card,
                    'img_front' => $info->img_front,
                    'img_back' => $info->img_back,
                    'is_edit' => $info->status == 3 ? 1 : 0,
                    'status' => getExamineStatus($info->status),
                    'reject_msg' => $info->status == 3 ? $info->reject_msg : ''
                ];
            }
        }

        return Result::success('success', $data);
    }

    public function save(): Response
    {
        $param = $this->request->post();
        try {
            $this->validate($param, 'UserAuth');
        } catch (ValidateException $e) {
            return Result::fail($e->getError());
        }

        return Result::fastReturn(UserAuthModel::add($param, $this->user));
    }
}